<template>
  <div class="app-container" ref="appcontainer">
    <div class="btn">
      <el-button type="primary" @click="handleAddService">添加服务</el-button>
      <el-button type="primary" @click="showTimeSet" >预约时间设置</el-button>
    </div>
    <el-table v-loading="loading" :height="tableHeight" :data="orderList">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="一级分类" align="center" prop="classifyId">
        <template slot-scope="scope">
          <p>{{ getClassName(scope.row.classifyId) }}</p>
        </template>
      </el-table-column>
      <el-table-column label="二级分类" align="center" prop="classifyCid">
        <template slot-scope="scope">
          <p>{{ getClassName(scope.row.classifyCid) }}</p>
        </template>
      </el-table-column>
      <el-table-column label="项目等级" align="center" prop="grade" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleFix(scope.row)"
            >修改</el-button
          >
          <el-button type="text" size="small" @click="handleDel(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleClose"
    >
      <el-form
        :inline="true"
        :model="formInline"
        label-width="80px"
        class="demo-form-inline"
      >
        <div>
          <el-form-item label="一级分类">
            <el-select
              v-model="formInline.classifyId"
              placeholder="请选择分类"
              @change="handleOneClassChange"
            >
              <el-option
                v-for="item in classSelect"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="二级分类" v-if="sonclass.length > 0">
            <el-select
              v-model="formInline.classifyCid"
              placeholder="请选择分类"
            >
              <el-option
                v-for="item in sonclass"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目级别">
            <!-- <el-input
              v-model="formInline.grade"
              placeholder="项目级别"
            ></el-input> -->
            <el-select
              v-model="formInline.grade"
              placeholder="请选择项目级别"
            >
              <el-option
                v-for="item in gradeoptions"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="价格">
            <el-input
              type="number"
              v-model="formInline.price"
              placeholder="价格"
            ></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="排序">
            <el-input
              type="number"
              v-model="formInline.sort"
              placeholder="排序"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="预约时间设置"
      :visible.sync="timeDialogVisible"
      width="800px"
      @close="handleTimeClose"
    >
    <!-- <el-form label-position="right" label-width="100px">
        <el-form-item label="是否允许预约" style="margin-top: 30px">
            <el-switch
            v-model="appointmentState"
            active-text="是"
            inactive-text="否">
            </el-switch>
          
        </el-form-item>
    </el-form> -->
      <el-transfer
        v-model="weeks"
        :data="weeksData"
        :titles="['星期', '已选中']"
      ></el-transfer>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="添加时间段" style="margin-top: 30px">
          <div>
            <el-time-select
              placeholder="起始时间"
              v-model="startTime"
              style="margin-right: 10px"
              :picker-options="{
                start: start,
                step: '00:30',
                end: end,
              }"
            >
            </el-time-select>
            <el-time-select
              placeholder="结束时间"
              v-model="endTime"
              style="margin-right: 10px"
              :picker-options="{
                start: start,
                step: '00:30',
                end: end,
                minTime: startTime,
              }"
            >
            </el-time-select>
            <el-button type="primary" @click="handleAddTime">添加</el-button>
          </div>
          <div v-for="(item,index) in timeFrames" :key="index">
            <div class="timelist">
              <div class="timelist-left">
                {{ item.startTime }} - {{ item.endTime }}
              </div>
              <el-button type="text" @click="handleDelTime(index)" >删除</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="不可约日期" style="margin-top: 30px">
          <div>
            <el-date-picker
                v-model="closeTime"
                style="margin-right: 10px;"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
            <el-button type="primary" @click="handleAddDate">添加</el-button>
          </div>
          <div v-for="(item,index) in closesDates" :key="index">
            <div class="timelist">
              <div class="timelist-left">
                {{ item.startDate }} - {{ item.endDate }}
              </div>
              <el-button type="text" @click="handleDelDate(index)" >删除</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="timeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTimeSet"
          >提 交</el-button
        >
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  reservationList,
  getClassify,
  doorserver,
  doorserverDel,
  doorserverPut,
  appointmentTime,
  appointmentEdit
} from "@/api/store/store";
export default {
  name: "Cash",
  data() {
    return {
      tableHeight: 0,
      // 遮罩层
      loading: true,
      orderList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      title: "添加上门服务",
      dialogVisible: false,
      formInline: {
        id: -1,
        grade: "",
        price: "",
        sort: "",
        classifyId: "",
        classifyCid: "",
      },
      classlist: [],
      classSelect: [],
      sonclass: [],
      timeDialogVisible: false,
      weeksData: [],
      weeks: [],
      timeFrames: [],
      closesDates: [],
      start: "",
      end: "",
      timeList: [],
      startTime: "",
      endTime: "",
      closeTime: "",
      appointmentState: true,
      gradeoptions: [
        {
          id: '普通',
          name: '普通'
        },
        {
          id: '中档',
          name: '中档'
        },
        {
          id: '高档',
          name: '高档'
        }
      ]
    };
  },
  created() {
    this.getList();
    this.calHeight();
    getClassify().then((res) => {
      this.classlist = res.rows;
      const list = [...res.rows];
      for (let i = list.length - 1; i >= 0; --i) {
        // console.log(list[i])
        if (list[i].parentId == 0) {
          console.log(list[i])
          this.classSelect.push(list[i]);
          list.splice(i, 1);
        }
      }
      for (let i = 0; i < list.length; ++i) {
        const id = list[i].parentId;
        const obj = this.classSelect.find((item) => {
          return item.id == id;
        });
        // console.log(obj)
        if (obj) {
          if (Object.prototype.hasOwnProperty.call(obj, "children")) {
            obj["children"].push(list[i]);
          } else {
            obj["children"] = [];
            obj["children"].push(list[i]);
          }
        }
      }
    });
    appointmentTime().then((res) => {
      let severalWeeks = res.data.appointmentVO.severalWeeks;
      severalWeeks = severalWeeks.map((item) => {
        return { ...item, key: item.weekKye, label: item.weekName };
      });
      this.weeksData = severalWeeks;
      severalWeeks.forEach((item) => {
        if (item.checked == "Y") {
          this.weeks.push(item.weekKye);
        }
      });

      this.timeFrames =
        res.data.appointmentVO.timeFrames == false
          ? []
          : res.data.appointmentVO.timeFrames;
      this.closesDates =
        res.data.appointmentVO.closesDates == false
          ? []
          : res.data.appointmentVO.closesDates;
      this.timeList = [...res.data.timeList, "24:00"];
      this.start = this.timeList[0];
      this.end = this.timeList[this.timeList.length - 1];

      this.appointmentState = res.data.appointmentVO.appointmentState == 'Y' ? true : false
    });
  },
  watch: {
    showSearch: "calHeight",
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    appointment() {
        appointmentTime().then((res) => {
        let severalWeeks = res.data.appointmentVO.severalWeeks;
        severalWeeks = severalWeeks.map((item) => {
            return { ...item, key: item.weekKye, label: item.weekName };
        });
        this.weeksData = severalWeeks;
        severalWeeks.forEach((item) => {
            if (item.checked == "Y") {
            this.weeks.push(item.weekKye);
            }
        });

        this.timeFrames =
            res.data.appointmentVO.timeFrames == false
            ? []
            : res.data.appointmentVO.timeFrames;
        this.closesDates =
            res.data.appointmentVO.closesDates == false
            ? []
            : res.data.appointmentVO.closesDates;
        this.timeList = [...res.data.timeList, "24:00"];
        this.start = this.timeList[0];
        this.end = this.timeList[this.timeList.length - 1];

        this.appointmentState = res.data.appointmentVO.appointmentState == 'Y' ? true : false
        });
    },
    getClassName(id) {
      const obj = this.classlist.find((item) => {
        return item.id == id;
      });
      if (obj) {
        return obj.classifyName;
      } else {
        return "";
      }
    },
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.appcontainer.getBoundingClientRect();
        // let height = this.$refs.queryForm.$el.offsetHeight;
        this.tableHeight = rect.height - 166;
      });
    },
    getList() {
      this.loading = true;
      reservationList(this.queryParams).then((res) => {
        this.total = res.total;
        this.orderList = res.rows;
        this.loading = false;
      });
    },
    apply(row) {
      this.$confirm("是否确认大框?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const id = row.id;
          applycash(id).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    handleAddService() {
      this.title = "添加上门服务";
      this.dialogVisible = true;
    },
    handleOneClassChange(val) {
      const obj = this.classSelect.find((item) => {
        return item.id == val;
      });
      if (obj) {
        if (Object.prototype.hasOwnProperty.call(obj, "children")) {
          this.sonclass = obj["children"];
        } else {
          this.sonclass = [];
        }
      } else {
        this.sonclass = [];
      }
      this.formInline.classifyCid = "";
    },
    handleClose() {
      this.formInline = {
        grade: "",
        price: "",
        sort: "",
        classifyId: "",
        classifyCid: "",
      };
    },
    submit() {
      if(this.formInline.classifyCid == "" || !this.formInline.classifyCid) {
        this.$message({
          message: '必须要有二级分类',
          type: "warning",
        })
        return
      }
      if (this.formInline.id && this.formInline.id != -1) {
        this.handleFixFn();
      } else {
        this.handleAdd();
      }
    },
    handleAdd() {
      const data = this.formInline;
      let msg = "添加成功";
      this.title = "添加上门服务";
      delete data.id;
      doorserver(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: msg,
            type: "success",
          });
          this.dialogVisible = false;
          this.getList();
        }
      });
    },
    handleFixFn() {
      const data = this.formInline;
      let msg = "修改成功";
      doorserverPut(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: msg,
            type: "success",
          });
          this.dialogVisible = false;
          this.getList();
        }
      });
    },
    handleDel(id) {
      this.$confirm("此操作将删除该服务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          doorserverDel(id).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    handleFix(row) {
      this.formInline = {
        id: row.id,
        grade: row.grade,
        price: row.price,
        sort: row.sort,
        classifyId: row.classifyId,
        classifyCid: row.classifyCid || "",
      };
      this.title = "修改上门服务";
      const obj = this.classSelect.find((item) => {
        return item.id == row.classifyId;
      });
      if (obj) {
        if (Object.prototype.hasOwnProperty.call(obj, "children")) {
          this.sonclass = obj["children"];
        } else {
          this.sonclass = [];
        }
      } else {
        this.sonclass = [];
      }
      this.dialogVisible = true;
    },
    handleAddTime() {
        if(!this.startTime) {
            this.$message({
                message: '请选择开始时间',
                type: 'warning'
            })
            return
        }
        if(!this.endTime) {
            this.$message({
                message: '请选择结束时间',
                type: 'warning'
            })
            return
        }
        this.timeFrames.push({
            startTime: this.startTime,
            endTime: this.endTime
        })
        this.startTime = ""
        this.endTime = ""
    },
    handleDelTime(index) {
        this.timeFrames.splice(index,1)
    },
    formatDate(dateVal) {
        const date = new Date(dateVal)
        const year = date.getFullYear()
        const month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
        const day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
        return year + '-' + month + '-' + day
    },
    handleAddDate() {
        if(!this.closeTime) {
            this.$message({
                message: '请选择日期',
                type: 'warning'
            })
            return
        }
        this.closesDates.push({
            startDate: this.formatDate(this.closeTime[0]),
            endDate: this.formatDate(this.closeTime[1])
        })
        this.closeTime = ""
    },
    handleDelDate(index) {
        this.closesDates.splice(index,1)
    },
    showTimeSet() {
        this.appointment()
        this.timeDialogVisible = true
    },
    handleTimeClose() {},
    submitTimeSet() {
      if(this.timeFrames.length == 0) {
        this.$message({
          message: '请添加时间段',
          type: 'warning'
        })
        return
      }
        this.weeks.forEach(item => {
            const obj = this.weeksData.find(i => {
                return i.weekKye == item
            })
            if(obj) {
                obj.checked = 'Y'
            }
        })
        const data = {
            technicianId: "",
            appointmentState: this.appointmentState ? 'Y' : 'N',
            timeFrames: this.timeFrames,
            closesDates: this.closesDates,
            severalWeeks: this.weeksData
        }
        appointmentEdit(data).then(res => {
            if(res.code == 200) {
                this.$message({
                    message: '设置成功',
                    type: "success",
                })
            }
            this.timeDialogVisible = false
        })
    }
  },
};
</script>
<style scoped>
.btn {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.timelist {
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
    